﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO.Ports;
using SuporeSliplampApp.Util;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// LightControlView.xaml 的交互逻辑
    /// </summary>
    public partial class LightControlView : Window
    {
        SerialPort serialPort = null;
        bool isOpen = false;
        string End = Environment.NewLine;
        public LightControlView()
        {
            InitializeComponent();
            DataContext = this;
            List<string> comlist = new List<string>();
            List<string> bateratelist = new List<string>();
            for (int i = 0; i < 20; i++)
            {
                comlist.Add("COM" + (i + 1).ToString());
            }
            bateratelist.Add(9600.ToString());
            bateratelist.Add(19200.ToString());
            bateratelist.Add(38400.ToString());
            bateratelist.Add(57600.ToString());
            port.ItemsSource = comlist;
            bate.ItemsSource = bateratelist;
        }

        /// <summary>
        /// 左右眼查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void query_Click(object sender, RoutedEventArgs e)
        {
            byte[] buffer = new byte[] { 0xFE, 0x2, 0x0, 0x0, 0x0, 0x0, 0x2, 0xFF };
            SengInstructions(buffer);
        }
        /// <summary>
        /// 拍照按钮查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void photo_Click(object sender, RoutedEventArgs e)
        {
            byte[] buffer = new byte[] { 0xFE, 0x3, 0x0, 0x0, 0x0, 0x0, 0x3, 0xFF };
            SengInstructions(buffer);
        }
        /// <summary>
        /// 红外灯控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void redlight_Click(object sender, RoutedEventArgs e)
        {
            int sliderVue = (int)slider.Value;
            int crcValue = (4 + sliderVue) % 255;
            string hex = sliderVue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040000" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);           
            SengInstructions(buffer);
        }

        /// <summary>
        /// 补光灯控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lacklight_Click(object sender, RoutedEventArgs e)
        {
            int sliderVue = (int)slider.Value;
            int crcValue = (5 + sliderVue) % 255;
            string hex = sliderVue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040100" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);
            SengInstructions(buffer);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void quit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void clear_Click(object sender, RoutedEventArgs e)
        {
            sendText.SelectAll();
            sendText.Selection.Text = "";
            receiveText.SelectAll();
            receiveText.Selection.Text = "";
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void con_Click(object sender, RoutedEventArgs e)
        {
            closePort();
            serialPort = new SerialPort(port.SelectedItem.ToString(), Convert.ToInt32(bate.SelectedValue), Parity.None, 8, StopBits.One);
            serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            try
            {
                serialPort.Open();
                isOpen = true;
                receiveText.AppendText("串口打开成功!" + End);

            }
            catch (Exception ex)
            {
                receiveText.AppendText("串口打开失败：" + ex.ToString() + End);
            }
            finally
            {

            }
        }

        private void close_Click(object sender, RoutedEventArgs e)
        {
            closePort();
        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadExisting();
            string s = string.Empty;
            byte[] encodedBytes = Encoding.UTF8.GetBytes(data);           
            for (int i = 0; i < encodedBytes.Length; i++)
            {
                s = s+ encodedBytes[i]+" ";
            }
            s += End;
            Dispatcher.Invoke(new Action(() => { receiveText.AppendText(s); }));


        }
        //private void test()
        //{
        //    byte[] byteArr = { 72, 101, 108, 108, 111 };
        //    string str = string.Empty;
        //    for (int i = 0; i < byteArr.Length; i++)
        //    {
        //        str = str + byteArr[i]+" ";
        //    }
        //}
        /// <summary>
        /// 红外滤光片选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pickRed_Click(object sender, RoutedEventArgs e)
        {
            byte[] buffer = new byte[] { 0xFE, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0xFF };
            SengInstructions(buffer);
        }
        /// <summary>
        /// 全透滤光片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pickLight_Click(object sender, RoutedEventArgs e)
        {
            byte[] buffer = new byte[] { 0xFE, 0x1, 0x1, 0x0, 0x0, 0x0, 0x2, 0xFF };
            SengInstructions(buffer);
        }

        private void SengInstructions(byte[] data)
        {
            if (isOpen)
            {
                SerialPortWrite(data);
            }
            else
            {
                MessageBox.Show("请先连接串口!");
            }
        }

        private bool SerialPortWrite(byte[] data)
        {
            try
            {
                string res = string.Join(" ", data);
                serialPort.Write(data, 0, data.Length);
                Dispatcher.Invoke(new Action(() => { sendText.AppendText("发送成功: "+res + End); }));
                
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(new Action(() => { sendText.AppendText("发送失败：" + ex.ToString() + End); }));
                //sendText.AppendText("发送失败：" + ex.ToString() + End);
                return false;
            }
            return true;
        }

        private byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            byte[] returnBytes = new byte[hexString.Length / 2];
            if (hexString.Length % 2 == 0)
            {
                for (int i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                }
            }
            return returnBytes;
        }

        private void close_Click_1(object sender, RoutedEventArgs e)
        {
            closePort();
            this.Close();
        }

        private void closePort()
        {

            try
            {
                if (serialPort != null)
                {
                    if (serialPort.IsOpen)
                        serialPort.Close();
                    serialPort.Dispose();
                }
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            int intValue = Convert.ToInt32(slider.Value);
            Dispatcher.Invoke(new Action(() => { sliderTXT.Text = intValue.ToString(); }));
            int crcValue = (4 + intValue) % 255;
            string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040000" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);
            SengInstructions(buffer);

        }

        private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            int intValue = Convert.ToInt32(slider2.Value);
            Dispatcher.Invoke(new Action(() => { sliderTXT2.Text = intValue.ToString(); }));
            int crcValue = (5 + intValue) % 255;
            string hex = intValue.ToString("X").ToUpper().PadLeft(2, '0');
            string hex1 = crcValue.ToString("X").ToUpper().PadLeft(2, '0');
            string s = "FE040100" + hex + "00" + hex1 + "FF";
            byte[] buffer = ConvertHexStringToBytes(s);
            SengInstructions(buffer);
        }
    }
}
